﻿using AutoMapper;
using Dapper;
using MediatR;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using MyMES.Domain.W.Liststructure;
using MyMES.Error;
using MyMES.Infrastructure;
using MyMES.Infrastructure.Interface;
using MyMES.Writer.API.Application.Commends.W.realize;
using MySqlX.XDevAPI.Common;
using System.Data;

namespace MyMES.Writer.API.Application.CommendHandlers.W.realize
{
    public class AddBillingmanagementCommandHanders : IRequestHandler<AddBillingmanagementCommands, APIResult<Billingmanagement>>
    {
        private readonly IBaseRepository<Billingmanagement> baseRepository;
        private readonly IMapper mapper;
        public DatabaseContext db;

        public AddBillingmanagementCommandHanders(IBaseRepository<Billingmanagement> baseRepository, IMapper mapper, DatabaseContext db)
        {
            this.baseRepository = baseRepository;
            this.mapper = mapper;
            this.db = db;
        }

        /// <summary>
        /// 添加开票信息管理
        /// </summary>
        /// <param name="request">添加开票</param>
        /// <param name="cancellationToken">2025年4月14日17:23:46</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<Billingmanagement>> Handle(AddBillingmanagementCommands request, CancellationToken cancellationToken)
        {
            APIResult<Billingmanagement> result = new APIResult<Billingmanagement>();

            using (var connection = db.Connection)
            {
                if (connection.State != ConnectionState.Open)
                {
                    connection.Open();
                }
                request.Createid ??= new List<int>();
                using (var transaction = connection.BeginTransaction())
                {
                    try
                    {
                        var Billing = mapper.Map<Billingmanagement>(request);

                        // 假设 Bid 是自增主键，不插入 Bid
                        var sql = "insert into Billingmanagement (BillingNumber, BillingName, Billingtype, BillingTime, Collectticket, Invoicenumber, Remark, IsDelete) values (@BillingNumber, @BillingName, @Billingtype, @BillingTime, @Collectticket, @Invoicenumber, @Remark, @IsDelete); SELECT LAST_INSERT_ID();";
                        var BillingId = await connection.ExecuteScalarAsync<int>(
                            sql,
                            Billing,
                            transaction);

                        // 检查 BillingId 是否有效
                        if (BillingId > 0)
                        {
                            if (request.Createid.Any())
                            {
                                const string sql1 = @"insert into BillingSales (Bid, SalesId) values (@Bid, @SalesId)";
                                foreach (var SalesId in request.Createid)
                                {
                                    await connection.ExecuteAsync(
                                        sql1,
                                        new
                                        {
                                            Bid = BillingId,
                                            SalesId = SalesId,
                                        }, transaction);
                                }
                            }
                        }
                        else
                        {
                            throw new Exception("插入 Billingmanagement 表失败，无法获取有效的 BillingId");
                        }

                        transaction.Commit();
                        var newdata = await connection.QueryFirstOrDefaultAsync<Billingmanagement>(
                            "select * from Billingmanagement where Bid = @Bid", new { Bid = BillingId });

                        result.Code = APIEnum.添加成功;
                        result.Msg = $"开票成功，销售订单数：{request.Createid.Count}";
                        result.data = newdata;
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        throw new Exception("添加开票信息失败，事务已回滚", ex);
                    }
                }
            }

            return result;
        }
    }
}